import requests
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import time
import datetime
import json


def cookie():  # 获取请求参数
    list_canshu = []
    chrome_options = Options()
    # chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
    # chrome_options.add_experimental_option("useAutomationExtension", False)

    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--no-sandbox")
    # rizhi=chrome_options.add_argument('--log-level=3')
    chrome_options.add_argument("--no-sandbox")
    browser = webdriver.Chrome(options=chrome_options)
    # browser = webdriver.Chrome()
    browser.get('https://www.4kmiles.com/console/dashboard')
    time.sleep(10)
    # 输入账户密码
    browser.find_elements_by_class_name('el-input__inner')[0].click()
    browser.find_elements_by_class_name('el-input__inner')[0].send_keys('nicolechow1993@163.com')
    browser.find_elements_by_class_name('el-input__inner')[1].click()
    browser.find_elements_by_class_name('el-input__inner')[1].send_keys('nicolez123')
    browser.find_element_by_xpath('//button[@class="el-button login-btn el-button--primary"]').send_keys(Keys.ENTER)
    time.sleep(10)
    cookie = [item["name"] + "=" + item["value"] for item in browser.get_cookies()]
    print(cookie)
    browser.quit()

    for i in cookie:
        if 'acc_t' in i:
            canshu = 'Bearer ' + i[6:]
            list_canshu.append(canshu)
            print(canshu)
    return list_canshu[0]


class Four:
    def __init__(self):
        self.cookie = cookie()

        self.headers = {
            'referer': 'https://www.4kmiles.com/console/dashboard',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36',
            'authorization': f'{self.cookie}'
        }

        self.py01 = False
        self.py02 = False
        self.py03 = False
        self.py04 = False
        self.today = datetime.date.today()
        self.oneday1 = datetime.timedelta(days=1)
        self.yesterday1 = self.today - self.oneday1
        self.oneday2 = datetime.timedelta(days=32)
        self.yesterday2 = self.today - self.oneday2
        # 格式化成2016-03-20 11:45:39形式
        self.newtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

        self.list01 = []
        self.list002 = []
        self.list03 = []
        # list04 = []
        self.list20 = []
        self.list21 = []
        self.list22 = []
        self.listshujv = []
        self.listshujv1 = []
        self.listshujv2 = []
        self.listshujv3 = []


    def all_load(self):#总路径
        url = f'https://www.4kmiles.com/api2/api/SellerAccount/GetCurrentUserSellerAccountList'
        all=requests.get(url,headers=self.headers).json()
        for i01 in all["result"]:
            id = i01["id"]
            sellerName = i01["sellerName"]
            print('*' * 30, sellerName)
            if sellerName != 'WSZCH':
                url01 = f'https://www.4kmiles.com/api2/api/Product/GetParentAsinPageList?queryParam.accountId={id}&pagination.rowsPerPage=10&pagination.currentPage=1&queryParam.IsListingView=true&queryParam.startDate={self.yesterday1}&queryParam.endDate={self.yesterday1}&queryParam.stockStatus=InStock&pagination.sortField=TodayOrders&pagination.sortType=desc'
                self.page(url01,id,sellerName)
    def page(self,url01,id,sellerName):#各账号页码数
        all_page=requests.get(url=url01,headers=self.headers).json()
        num01 = all_page["result"]["totalCount"]
        if num01 % 100 != 0:
            num02 = int(num01 / 100) + 1
            # print(id,'num',num02)

            for i in range(1, num02 + 1):
                url02 = f'https://www.4kmiles.com/api2/api/Product/GetAsinReportList?queryParam.accountId={id}&pagination.rowsPerPage=100&pagination.currentPage={i}&queryParam.isFba=true&queryParam.productStatus=InStock&queryParam.startDate=2021-10-12&queryParam.endDate=2021-10-12'
                url02 = f'https://www.4kmiles.com/api2/api/Product/GetParentAsinPageList?queryParam.accountId={id}&pagination.rowsPerPage=100&pagination.currentPage={i}&queryParam.IsListingView=true&queryParam.startDate={self.yesterday1}&queryParam.endDate={self.yesterday1}&queryParam.stockStatus=InStock&pagination.sortField=TodayOrders&pagination.sortType=desc'
                self.fa_one(url02,sellerName)

        else:
            num02 = int(num01 / 100)

            for i in range(1, num02 + 1):
                url02 = f'https://www.4kmiles.com/api2/api/Product/GetParentAsinPageList?queryParam.accountId={id}&pagination.rowsPerPage=100&pagination.currentPage={i}&queryParam.IsListingView=true&queryParam.startDate={self.yesterday1}&queryParam.endDate={self.yesterday1}&queryParam.stockStatus=InStock&pagination.sortField=TodayOrders&pagination.sortType=desc'
                self.fa_one(url02, sellerName)
    def fa_one(self,url02,sellerName):  # 父asin首页数据
        response=requests.get(url=url02,headers=self.headers).json()
        zong = response['result']['data']
        # print('zong', zong)
        for j in zong:
            # print(j)
            isFba = j["isFba"]
            if isFba == 1:
                isFba = 'FBA'
            elif isFba == 2:
                isFba = 'FBM'
            else:
                isFba = ''
            id = j["id"]
            asinId = j["asinId"]
            try:
                title = j["title"].replace("\n", "").replace("\r", "")
            except Exception as g:
                title = 'None'

            accountId = j['accountId']
            asin = j["asin"]
            self.list03.append(asin)
            sku = j["sku"]
            site = j["site"]
            productId = j["productId"]
            accountName = j['accountName']
            # 可售库存
            available = j['available']
            # 预留库存
            reserved = j['reserved']
            # 预留订单
            customerOrdersReservedQty = j['customerOrdersReservedQty']
            # 转运中
            reservedTransfersQty = j['reservedTransfersQty']
            # 处理中
            reservedProcessingQty = j['reservedProcessingQty']
            # 不可售库存
            unvailable = j['unvailable']
            # 图片
            try:
                imagePath = j['imagePath']
            except Exception as g:
                imagePath = 'None'
            # 分组
            productGroup = j['productGroup']
            # listing评分1
            reviewScore = j['reviewScore']
            # listing评分2
            reviewCount = j['reviewCount']
            # 在途库存已创建
            workInbound = j['workInbound']
            # 在途库存已发货
            shipInbound = j['shipInbound']
            # 在途库存接受中
            inbound = j['inbound']

            fa_guolv = asin + sku + site + sellerName + str(self.yesterday1)
            fa_guolv = fa_guolv.replace(' ', '')
            # print('fa_goulv',fa_guolv)
            if fa_guolv not in self.list22:
                self.list22.append(fa_guolv)

    def son_one(self):  # 子asin首页数据
        pass

    def fa_two(self):  # 父asin详情页数据
        pass

    def son_two(self):  # 子asin详情页数据
        pass

    def fa_one_into(self):  # 父asin首页数据插入数据库
        pass

    def son_one_into(self):  # 子asin首页数据插入数据库
        pass

    def fa_two_into(self):  # 父asin详情页数据插入数据库
        pass

    def son_two_into(self):  # 子asin详情页数据插入数据库
        pass




if __name__ == '__main__':
    finish = Four()
    finish.
